package com.gzmu.myprint.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gzmu.myprint.wx.api.AesException;
import com.gzmu.myprint.wx.api.WXBizMsgCrypt;
import com.gzmu.myprint.wx.msg.resp.TextMessage;
import com.gzmu.myprint.wx.msg.util.MessageUtil;
import com.gzmu.myprint.wx.servicet.CoreService;
import com.gzmu.myprint.wx.util.ParamesAPI;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;



@Controller
@RequestMapping("/")
public class WeixinController {
	/**
	 * 验证服务器正确性，这里仅仅返回服务器字符串，没有验证
	 * @param request 请求对象
	 * @param response 响应对象
	 * @throws IOException
	 */
	@RequestMapping(value="/conwx",method=RequestMethod.GET)
	public void messageGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 微信加密签名
		String msg_signature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		PrintWriter out = response.getWriter();
		// 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		String echostr_ret=null;
		if (msg_signature==null||timestamp==null||nonce==null||echostr==null){
			echostr_ret = "no parameters";
		}else{
			try{
				WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(ParamesAPI.token, ParamesAPI.encodingAESKey, ParamesAPI.corpId);
				// 验证URL函数
				echostr_ret=wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
			}catch (AesException e) {
				e.printStackTrace();
			}
			if (echostr_ret == null) {
				// echostr_ret为空，赋予token
				echostr_ret = ParamesAPI.token;
			}
		}
		// 拼接请求参数
		String str = msg_signature+" "+timestamp+" "+nonce+" "+echostr;
		// 打印参数+地址+result
		System.out.println("Exception:"+echostr_ret+" "+ request.getRequestURL()+" "+"FourParames:"+str);
		// 回调的数据
		out.print(echostr_ret);
		out.close();
	}

	/**
	 * 这个方法里面解析微信发送过来的信息，并按照微信消息格式返回给微信
	 * @param request 请求对象
	 * @param response 响应对象
	 * @return
	 */
	@RequestMapping(value="/conwx",method=RequestMethod.POST)
	public void message(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 微信加密签名
		String msg_signature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		//从请求中读取整个post数据
		InputStream inputStream = request.getInputStream();
		//commons.io.jar 方法
		String Post = IOUtils.toString(inputStream, "UTF-8");
		// Post打印结果
		System.out.println(Post);

		String inmsg = null;
		String outmsg = null;
		WXBizMsgCrypt wxcpt = null;
		try {
			wxcpt = new WXBizMsgCrypt(ParamesAPI.token,ParamesAPI.encodingAESKey,ParamesAPI.corpId);
			inmsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, Post);
		} catch (AesException e) {
			e.printStackTrace();
		}
		TextMessage textMessage = CoreService.processRequest(inmsg);
		if(textMessage==null){
			return ;
		}
		String content = textMessage.getContent();
		String respXml = MessageUtil.textMessageToXml(textMessage);
		try {
			content = wxcpt.EncryptMsg(respXml, timestamp, nonce);
		} catch (AesException e) {
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.print(content);
		out.close();
	}
}
